﻿using DBUtility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Utilities;
using WeChat.Models;

namespace WeChat.Controllers
{
    public class WeiXinController : Controller
    {
        DbHelper helper = new DbHelper("3");
        log4net.ILog logger = log4net.LogManager.GetLogger("WeChatConnect");
        ///声明Log全局变量
        private static string token = ConfigurationManager.AppSettings["wechatToken"];
        private readonly static string appid = ConfigurationManager.AppSettings["appid"];
        private readonly static string secret = ConfigurationManager.AppSettings["AppSecret"];

        static string Version = "1.0.0";
        static string oatoken = "0e28d0ae-0c08-489d-8247-ce27fcea9e4d";
        //static string userId = "324EFCFA87F40696";
        static string userId = "C254431762D8C3E4";

        private static string url = ConfigurationManager.AppSettings["url"];

        [HttpGet]
        //[ActionName("ProcessRequest")]
        public ActionResult Index()
        {
            try
            {
                string ss = token + "-" + appid + "-" + secret;

                var postStr = "";

                logger.Debug("进入主方法Index:");
                var result = System.Web.HttpContext.Current.Request.InputStream;//获取微信返回的字节流
                var b = new byte[result.Length];
                postStr = Encoding.UTF8.GetString(b);
                logger.Debug("微信返回字节流:" + postStr);

                string signature = Request.QueryString["signature"];
                string timestamp = Request.QueryString["timestamp"];
                string nonce = Request.QueryString["nonce"];
                string echostr = Request.QueryString["echostr"];

                logger.Debug("signature:" + signature);

                logger.Debug("timestamp:" + signature);
                logger.Debug("nonce:" + nonce);
                logger.Debug("echostr:" + echostr);
                string EchoStr = Valid(signature, timestamp, nonce, echostr, token);

                if (!string.IsNullOrEmpty(EchoStr))
                {
                    logger.Debug("验证成功:");
                    return Content(echostr);
                }
                else
                {
                    logger.Debug("验证失败:");
                    return Content("验证失败！");
                }
            }
            catch (Exception ex)
            {
                return Content(ex.ToString());
            }
            return View();
        }

        /// <summary>
        /// 判断是否来自于微信
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        public string Valid(string signature, string timestamp, string nonce, string echostr, string token)
        {
            if (CheckSignature(signature, timestamp, nonce, token))
            {
                if (!string.IsNullOrEmpty(echostr))
                {
                    return echostr;
                }
            }

            return "";
        }



        /// <summary>
        /// 验证开发者，只需验证一次
        /// </summary>
        /// <returns></returns>
        private bool CheckSignature()
        {
            logger.Debug("验证开发者！");
            var signature = Request.QueryString["signature"];
            var timestamp = Request.QueryString["timestamp"];
            var nonce = Request.QueryString["nonce"];
            string[] arrTmp = { token, timestamp, nonce };

            Array.Sort(arrTmp);    //字典排序

            var tmpStr = String.Join("", arrTmp);

            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");  //SHA1加密

            if (string.IsNullOrEmpty(tmpStr))
                return false;
            tmpStr = tmpStr.ToLower();

            if (tmpStr == signature)
                return true;

            return false;
        }

        /// <summary>
        /// 验证微信签名
        /// </summary>
        /// * 将token、timestamp、nonce三个参数进行字典序排序
        /// * 将三个参数字符串拼接成一个字符串进行sha1加密
        /// * 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。
        /// <returns></returns>
        public bool CheckSignature(string signature, string timestamp, string nonce, string token)
        {
            //signature = Request.QueryString["signature"];
            //timestamp = Request.QueryString["timestamp"];
            //nonce = Request.QueryString["nonce"];
            string[] ArrTmp = { token, timestamp, nonce };
            Array.Sort(ArrTmp); //字典排序
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 检查微信id是否绑定了派生集团账户
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        public bool CheckWeChat(string openid)
        {
            string sql = string.Format(@"select * from groupuser where wechat='{0}'", openid);
            //SqlParameter[] par=new SqlParameter[1];
            //string sql = string.Format(@"select * from groupuser where wechat=@wechat");
            //SqlParameter[] paramArray = new SqlParameter[1];
            //paramArray[0] = new SqlParameter("@wechat", openid);
            //bool result = DbHelper.Exists(sql,paramArray);
            bool result = DbHelper.Exists(sql);
            logger.Debug("验证微信号sql：" + sql);
            logger.Debug("验证微信号结果：" + result);
            return result;
        }

        /// <summary>
        /// 检查手机号或邮箱是否派生用户
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        public bool CheckUserName(string userName)
        {
            //防止sql注入
            string sql = "select * from groupuser where tel=@keywords or jobnumber=@keywords";
            SqlParameter[] parameters = {
    new SqlParameter("@keywords", SqlDbType.NVarChar) };
            parameters[0].Value = userName;

            //string sql = string.Format(@"select * from groupuser where tel='@keywords' or email='@keywords'");
            //SqlParameter[] paramArray = new SqlParameter[1];
            //paramArray[0] = new SqlParameter("@keywords", userName);


            //string sql = string.Format(@"select * from groupuser where tel='{0}' or email='{0}'", userName);


            bool result = DbHelper.Exists(sql.ToString(), parameters);
            return result;
        }

        /// <summary>
        /// 个人中心
        /// </summary>
        /// <returns></returns>
        public ActionResult PersonalCenter()
        {
            return View();
        }

        /// <summary>
        /// 绑定页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Binding(string openid)
        {
            //string aa = @"{'Version':'1.0.0','Token':'0e28d0ae-0c08-489d-8247-ce27fcea9e4d','UserId':'1E8507BF2CEB0ABD','Data':'{\'UserName\':\'" + openid + "\\'}'}";
            //string bb =string.Format(@"{'Version':'1.0.0','Token':'0e28d0ae-0c08-489d-8247-ce27fcea9e4d','UserId':'1E8507BF2CEB0ABD','Data':'{\'UserName\':\'{0}\'}'}",openid);
            //string openid = Request.QueryString["openid"];
            //if (string.IsNullOrWhiteSpace(openid))
            //    openid = "oqzWd1MMTl2ERBtyUAXaA8nbseo0";
            ViewData["openid"] = openid;
            return View();
        }

        [HttpPost]
        public ActionResult Binding(string userName, string openid)
        {
            string action = url + "CheckUserName";
            //string aa = @"{'Version':'1.0.0','Token':'0e28d0ae-0c08-489d-8247-ce27fcea9e4d','UserId':'1E8507BF2CEB0ABD','Data':'{\'UserName\':\'" + userName + "\\'}'}";

            StringBuilder jsonStr = new StringBuilder();
            jsonStr.Append("{");
            jsonStr.AppendFormat("\"Version\":\"" + Version + "\",");
            jsonStr.AppendFormat("\"Token\":\"" + token + "\",");
            jsonStr.AppendFormat("\"UserId\":\"" + userId + "\",");
            jsonStr.AppendFormat("\"Data\":");
            jsonStr.Append("\"{");
            jsonStr.AppendFormat("\\\"UserName\\\":\\\"" + userName + "\\\",");
            jsonStr.AppendFormat("\\\"oppid\\\":\\\"" + openid + "\\\",");
            jsonStr.Append("}\"");
            jsonStr.Append("}");








            bool result = false;
            string message = "";
            if (string.IsNullOrWhiteSpace(userName))
                return Json(new { success = result, message = "请输入手机号或工号" });


            var json = PostMoths(action, jsonStr.ToString());
            var data = JsonConvert.DeserializeObject<Respon>(json);

            if (data.Data == "True")
            //if (CheckUserName(userName))
            {
                //string isBindingSql = string.Format(@"select top 1 wechat from groupuser where  tel='{0}' or jobnumber='{0}'", userName);
                //string wechat = (string)helper.ExecuteScalar(isBindingSql);
                action = url + "CheckBinding";

                var isbindjson = PostMoths(action, jsonStr.ToString());
                var isbingddata = JsonConvert.DeserializeObject<Respon>(isbindjson);
                //if (string.IsNullOrWhiteSpace(wechat))
                if (string.IsNullOrWhiteSpace(isbingddata.Data))
                {

                    //string sql = string.Format(@"update groupuser set wechat='{0}',IsBinding=0 where tel='{1}' or jobnumber='{1}'", openid, userName);
                    //int count = helper.ExecuteNonQuery(sql);

                    action = url + "Binding";
                    var bindjson = PostMoths(action, jsonStr.ToString());
                    var bingddata = JsonConvert.DeserializeObject<Respon>(bindjson);


                    //if (count > 0)
                    //{
                    if (bingddata.Data == "0")
                    {
                        result = true;
                        message = "验证成功";
                    }
                    else
                    {
                        result = false;
                        message = "员工档案信息不匹配";
                    }
                }
                else
                {
                    result = false;
                    message = "验证失败,该账户已经被绑定";
                }
            }
            else
            {
                result = false;
                message = "员工档案信息不匹配";
            }

            return Json(new { success = result, message = message }, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// OAuthSnsApiUserInfo 个人中心
        /// </summary>
        /// <returns></returns>
        public ActionResult OAuthSnsApiUserInfo()
        {
            string code = Request.QueryString["code"];
            UserInfo user = new UserInfo();
            try
            {
                if (!string.IsNullOrEmpty(code))
                {
                    logger.Debug("验证开始0");
                    OAuthToken oauthToken = HttpUtility.Get<OAuthToken>(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code));
                    logger.Debug("oauthToken:" + oauthToken);
                    if (oauthToken != null && !string.IsNullOrEmpty(oauthToken.openid) && !string.IsNullOrEmpty(oauthToken.access_token))
                    {
                        //验证微信号是否绑定了派生，绑定进入个人中心，没有绑定则进入绑定页面

                        StringBuilder jsonStr = new StringBuilder();
                        jsonStr.Append("{");
                        jsonStr.AppendFormat("\"Version\":\"" + Version + "\",");
                        jsonStr.AppendFormat("\"Token\":\"" + token + "\",");
                        jsonStr.AppendFormat("\"UserId\":\"" + userId + "\",");
                        jsonStr.AppendFormat("\"Data\":");
                        jsonStr.Append("\"{");
                        jsonStr.AppendFormat("\\\"oppid\\\":\\\"" + oauthToken.openid + "\\\",");
                        jsonStr.Append("}\"");
                        jsonStr.Append("}");
                        string action = url + "CheckWeChat";
                        var check_json = PostMoths(action, jsonStr.ToString());
                        var check_data = JsonConvert.DeserializeObject<Respon>(check_json);
                        if (check_data.Data == "True")
                        //if (CheckWeChat(oauthToken.openid))
                        {
                            OAuthUserInfo userInfo = Get<OAuthUserInfo>(string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", oauthToken.access_token, oauthToken.openid));
                            //                            string sql = string.Format(@"select position from groupuser where wechat='{0}';insert into [SearchLog](SearchId,UserId,WeChat,SearchTime)
                            //values('{2}','{3}','{4}',getDate());", oauthToken.openid, Guid.NewGuid(), null,oauthToken.openid);


                            //                            string sql = string.Format(@"select position from groupuser where wechat='{0}';  insert into [SearchLog](SearchId,UserId,WeChat,SearchTime)
                            //values('{1}',null,'{2}',getDate())", oauthToken.openid, Guid.NewGuid(), oauthToken.openid);
                            //string position = (string)helper.ExecuteScalar(sql);




                            action = url + "Position";
                            var json = PostMoths(action, jsonStr.ToString());
                            var data = JsonConvert.DeserializeObject<Respon>(json);

                            //if (string.IsNullOrWhiteSpace(position))
                            //    ViewData["position"] = "π";
                            //else
                            //    ViewData["position"] = position;


                            if (string.IsNullOrWhiteSpace(data.Data))
                            {
                                user.position = "π";
                                //ViewData["position"] = "π";
                            }
                            else
                            {
                                user.position = data.Data;
                                //ViewData["position"] = data.Data;
                            }

                            if (userInfo != null)
                            {
                                user.headImage = userInfo.headimgurl;
                                user.openid = userInfo.openid;
                                user.nickName = userInfo.nickname;
                                //ViewData["headImage"] = userInfo.headimgurl;
                                //ViewData["openid"] = userInfo.openid;
                                //ViewData["nickName"] = userInfo.nickname;
                                //if (userInfo.sex == 0)
                                //{
                                //    ViewData["sex"] = "未知";
                                //}
                                //else if (userInfo.sex == 1)
                                //{
                                //    ViewData["sex"] = "男";
                                //}
                                //else
                                //{
                                //    ViewData["sex"] = "女";
                                //}
                                //ViewData["province"] = userInfo.province;
                                //ViewData["city"] = userInfo.city;
                                logger.Debug("用户信息--用户名:" + userInfo.nickname + "-用户图像:" + userInfo.headimgurl + "用户openid:" + userInfo.openid);
                            }
                            else
                            {

                            }
                        }
                        else
                        {
                            return Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=123456#wechat_redirect&openid={2}", appid, Server.UrlEncode("http://" + Request.Url.Host + Url.Action("Binding", new { openid = "" + oauthToken.openid + "" })), oauthToken.openid));
                        }

                        logger.Debug("oauthToken.openid:" + oauthToken.openid);

                    }
                    else
                    {
                    }
                }
                else
                {
                    logger.Debug("验证开始1");
                    return Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=123456#wechat_redirect", appid, Server.UrlEncode("http://" + Request.Url.Host + Url.Action("OAuthSnsApiUserInfo"))));
                }
            }
            catch (Exception ex)
            {
                ViewData["errmsg"] = ex.Message;
            }

            return View(user);
        }

        /// <summary>
        /// 个人成绩列表
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        public ActionResult MyScore(string openid)
        {
            MyScoreView model = new MyScoreView();
            //string sql = string.Format(@"select Theme,AchievementId from Achievement a left join groupuser g on g.userid=a.userid where g.wechat='{0}'", openid);
            //DataSet query = helper.GetDataSet(sql);
            StringBuilder jsonStr = new StringBuilder();
            jsonStr.Append("{");
            jsonStr.AppendFormat("\"Version\":\"" + Version + "\",");
            jsonStr.AppendFormat("\"Token\":\"" + token + "\",");
            jsonStr.AppendFormat("\"UserId\":\"" + userId + "\",");
            jsonStr.AppendFormat("\"Data\":");
            jsonStr.Append("\"{");
            jsonStr.AppendFormat("\\\"oppid\\\":\\\"" + openid + "\\\",");
            jsonStr.Append("}\"");
            jsonStr.Append("}");
            string action = url + "MyScore";
            var json = PostMoths(action, jsonStr.ToString());
            var data = JsonConvert.DeserializeObject<ScoreList>(json);

            List<Achievement> list = new List<Achievement>();
            //if (query.Tables[0].Rows.Count > 0)
            //{
            //    list = IListDataSet.ToList<Achievement>(query.Tables[0]);
            //}
            if (data.Data != null)
            {
                foreach (var v in data.Data)
                {
                    Achievement a = new Achievement();
                    a.AchievementId = v.AchievementId;
                    a.Theme = v.Theme;
                    list.Add(a);
                }
            }


            model.MyScoreList = list;
            return View(model);
        }

        public ActionResult ScoreDetail(string id)
        {

            string action = url + "ScoreDetail";
            StringBuilder jsonStr = new StringBuilder();
            jsonStr.Append("{");
            jsonStr.AppendFormat("\"Version\":\"" + Version + "\",");
            jsonStr.AppendFormat("\"Token\":\"" + token + "\",");
            jsonStr.AppendFormat("\"UserId\":\"" + userId + "\",");
            jsonStr.AppendFormat("\"Data\":");
            jsonStr.Append("\"{");
            //jsonStr.AppendFormat("\\\"oppid\\\":\\\"" + openid + "\\\",");
            jsonStr.AppendFormat("\\\"AchievementId\\\":\\\"" + id + "\\\",");
            jsonStr.Append("}\"");
            jsonStr.Append("}");
            var json = PostMoths(action, jsonStr.ToString());
            var data = JsonConvert.DeserializeObject<ResponDetail>(json);




            //string sql = string.Format(@"select CONVERT(VARCHAR(7),examinationtime,23) as examinationtime,Theme,Quarter,Score,Userid  from Achievement where AchievementId='{0}'", id);
            //DataSet query = helper.GetDataSet(sql);
            ScoreDetailView model = new ScoreDetailView();
            if (data.Data != null)
            {
                model.Theme = data.Data.Theme;
                model.Quarter = data.Data.Quarter;
                model.Score = data.Data.Score;
                //model.Userid = data.Data.Userid;
                model.Examinationtime = data.Data.Examinationtime;
                model.Ranking = data.Data.Ranking;
                model.Winning = data.Data.Winning;
                model.Title1 = data.Data.Title1;
                model.Domainurl1 = data.Data.Domainurl1;
                model.Url1 = data.Data.Url1;

                model.Title2 = data.Data.Title2;
                model.Domainurl2 = data.Data.Domainurl2;
                model.Url2 = data.Data.Url2;

                model.Title3 = data.Data.Title3;
                model.Domainurl3 = data.Data.Domainurl3;
                model.Url3 = data.Data.Url3;
            }






            //if (query.Tables[0].Rows.Count > 0)
            //{
            //    model.Theme = Convert.ToString(query.Tables[0].Rows[0]["Theme"]);
            //    model.Quarter = Convert.ToString(query.Tables[0].Rows[0]["Quarter"]);
            //    model.Score = Convert.ToString(query.Tables[0].Rows[0]["Score"]);
            //    model.Userid = Convert.ToString(query.Tables[0].Rows[0]["Userid"]);
            //    model.Examinationtime = Convert.ToString(query.Tables[0].Rows[0]["Examinationtime"]);
            //}

            //获取排名
            //            string rankSql = string.Format(@"select pm from(
            //	select rank() over(order by Score desc) as pm,* from Achievement where  CONVERT(VARCHAR(7),examinationtime,23)='{0}') s where userid='{1}'", model.Examinationtime, model.Userid);



            //model.Ranking = helper.ExecuteScalar(rankSql).ToString();

            //string countSql = string.Format(@"select count(1) from Achievement where  CONVERT(VARCHAR(7),examinationtime,23)='{0}'", model.Examinationtime);
            //string count = helper.ExecuteScalar(countSql).ToString();
            //double win = (1 - Convert.ToDouble(model.Ranking) / Convert.ToDouble(count));
            //model.Winning = string.Format("{0:0.00%}", win);

            //List<Recommend> list = new List<Recommend>();
            //string snallsql = string.Format(@"select top 3 * from [SmallRecommend] order by istop");
            //DataSet small_query = helper.GetDataSet(snallsql);
            //if (small_query.Tables[0].Rows.Count > 0)
            //{
            //    list = IListDataSet.ToList<Recommend>(small_query.Tables[0]);
            //}
            //if (list != null)
            //{
            //    model.Title1 = list[0].Title;
            //    model.Domainurl1 = list[0].Domainurl;
            //    model.Url1 = list[0].Url;

            //    model.Title2 = list[1].Title;
            //    model.Domainurl2 = list[1].Domainurl;
            //    model.Url2 = list[1].Url;

            //    model.Title3 = list[2].Title;
            //    model.Domainurl3 = list[2].Domainurl;
            //    model.Url3 = list[2].Url;
            //}

            //model.RecommendList = list;
            return View(model);
        }

        public ActionResult Eorr()
        {
            return View();
        }

        /**
 * OAuthSnsApiBase
 * **/
        public ActionResult OAuthSnsApiBase()
        {
            string code = Request.QueryString["code"];
            try
            {
                if (!string.IsNullOrEmpty(code))
                {

                    OAuthToken oauthToken = HttpUtility.Get<OAuthToken>(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code));

                    string accesstoken = string.Empty;
                    AccessToken token = HttpUtility.Get<AccessToken>(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret));

                    if (token != null && !string.IsNullOrEmpty(token.access_token))
                    {
                        accesstoken = token.access_token;
                    }

                    if (oauthToken != null && !string.IsNullOrEmpty(oauthToken.openid))
                    {

                        OAuthUserInfo userInfo = HttpUtility.Get<OAuthUserInfo>(string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", accesstoken, oauthToken.openid));
                        if (userInfo != null)
                        {

                            logger.Info("获取到用户信息nickName:" + userInfo.nickname);
                            ViewData["headImage"] = userInfo.headimgurl;
                            ViewData["openid"] = userInfo.openid;
                            ViewData["nickName"] = userInfo.nickname;
                            if (userInfo.sex == 0)
                            {
                                ViewData["sex"] = "未知";
                            }
                            else if (userInfo.sex == 1)
                            {
                                ViewData["sex"] = "男";
                            }
                            else
                            {
                                ViewData["sex"] = "女";
                            }
                            ViewData["province"] = userInfo.province;
                            ViewData["city"] = userInfo.city;
                        }
                        else
                        {
                            logger.Info("未获取到用户信息");
                        }
                    }
                    else
                    {
                        logger.Info("access_token:" + oauthToken.access_token + ",openid:" + oauthToken.openid);
                    }



                }
                else
                {
                    return Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=123456#wechat_redirect", appid, "http://" + Request.Url.Host + Url.Action("OAuthSnsApiBase")));
                }
            }
            catch (Exception ex)
            {
                logger.Info(ex.Message);
                ViewData["errmsg"] = ex.Message;
            }

            return View();
        }

        public ActionResult SnsApiBase()
        {
            string code = Request.QueryString["code"];
            try
            {
                if (!string.IsNullOrEmpty(code))
                {
                    OAuthToken oauthToken = HttpUtility.Get<OAuthToken>(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code));

                    string accesstoken = string.Empty;
                    AccessToken token = HttpUtility.Get<AccessToken>(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret));

                    if (token != null && !string.IsNullOrEmpty(token.access_token))
                    {
                        accesstoken = token.access_token;
                    }

                    if (oauthToken != null && !string.IsNullOrEmpty(oauthToken.openid))
                    {

                        OAuthUserInfo userInfo = HttpUtility.Get<OAuthUserInfo>(string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", accesstoken, oauthToken.openid));
                        if (userInfo != null)
                        {
                            ViewData["headImage"] = userInfo.headimgurl;
                            ViewData["openid"] = userInfo.openid;
                            ViewData["nickName"] = userInfo.nickname;
                            if (userInfo.sex == 0)
                            {
                                ViewData["sex"] = "未知";
                            }
                            else if (userInfo.sex == 1)
                            {
                                ViewData["sex"] = "男";
                            }
                            else
                            {
                                ViewData["sex"] = "女";
                            }
                            ViewData["province"] = userInfo.province;
                            ViewData["city"] = userInfo.city;
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                    }
                }
                else
                {
                    return Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=123456#wechat_redirect", appid, "http://" + Request.Url.Host + Url.Action("OAuthSnsApiBase")));
                }
            }
            catch (Exception ex)
            {
                ViewData["errmsg"] = ex.Message;
            }

            return View();
        }



        public T Get<T>(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "get";
            request.Timeout = 2000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);

            string result = sr.ReadToEnd();
            return JsonConvert.DeserializeObject<T>(result);


        }

        public class HttpUtility
        {
            public static T Get<T>(string url)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "get";
                request.Timeout = 2000;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);

                string result = sr.ReadToEnd();

                return JsonConvert.DeserializeObject<T>(result);


            }
        }

        public string PostMoths(string url, string param)
        {
            string strURL = url;
            System.Net.HttpWebRequest request;
            request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            string paraUrlCoded = param;
            byte[] payload;
            payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            request.ContentLength = payload.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(payload, 0, payload.Length);
            writer.Close();
            System.Net.HttpWebResponse response;
            response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.Stream s;
            s = response.GetResponseStream();
            string StrDate = "";
            string strValue = "";
            StreamReader Reader = new StreamReader(s, Encoding.UTF8);
            while ((StrDate = Reader.ReadLine()) != null)
            {
                strValue += StrDate + "\r\n";
            }
            return strValue;
        }
    }
}